package com.youdoneed.user.privacy;

import com.querydsl.sql.SQLExpressions;
import com.querydsl.sql.SQLQueryFactory;
import com.querydsl.sql.dml.SQLInsertClause;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.GlobalIdWorker;
import com.youdoneed.user.consts.PrivacyConst;
import com.youdoneed.user.model.Privacy;
import com.youdoneed.user.model.User;
import com.youdoneed.user.query.QPrivacy;
import com.youdoneed.user.query.QUser;
import com.youdoneed.user.vo.UserBasicPrivacy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author Ewing
 * @since 2017-04-21
 **/
@Service
@Transactional
public class PrivacyServiceImpl implements PrivacyService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PrivacyServiceImpl.class);

    @Autowired
    private SQLQueryFactory queryFactory;

    private QPrivacy qPrivacy = QPrivacy.Privacy;
    private QUser qUser = QUser.User;

    @Override
    public long setUserPrivacies(int type, String userId, String[] userIds) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("UserInformationIsEmpty");
        }
        queryFactory.delete(qPrivacy)
                .where(qPrivacy.userId.eq(userId))
                .execute();
        // 添加权限设置
        SQLInsertClause insert = queryFactory.insert(qPrivacy);
        for (int i = 0; i < userIds.length; i++) {
            Privacy privacy = new Privacy();
            privacy.setPrivacyId(GlobalIdWorker.nextString());
            privacy.setUserId(userId);
            privacy.setOtherId(userIds[i]);
            privacy.setType(type);
            privacy.setCreateTime(new Date());
            insert.populate(privacy)
                    .addBatch();
        }
        return insert.isEmpty() ? 0 : insert.execute();
    }

    @Override
    public List<User> getPrivacyAllowUsers(int type, String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("UserInformationIsEmpty");
        }
        return queryFactory.selectFrom(qUser)
                .join(qPrivacy)
                .on(qUser.userId.eq(qPrivacy.userId))
                .where(qPrivacy.userId.eq(userId))
                .where(qPrivacy.type.eq(type))
                .fetch();
    }

    @Override
    @CacheEvict(value = "User", key = "'User:'+#userPrivacyParam.userId", condition = "#userPrivacyParam!=null")
    public long setUserBasicPrivacy(UserBasicPrivacy userPrivacyParam) {
        if (userPrivacyParam == null || !StringUtils.hasText(userPrivacyParam.getUserId())) {
            throw new AppException("UserInformationIsEmpty");
        }
        // 创建一个新对象进行选择性更新
        User userBasicPrivacy = new User();
        // 用户个人资料隐私
        if (userPrivacyParam.getAllowMyInfo() != null) {
            userBasicPrivacy.setAllowMyInfo(userPrivacyParam.getAllowMyInfo());
        }
        if (userPrivacyParam.getAllowMyFriends() != null) {
            userBasicPrivacy.setAllowMyFriends(userPrivacyParam.getAllowMyFriends());
        }
        if (userPrivacyParam.getAllowMyVideo() != null) {
            userBasicPrivacy.setAllowMyVideo(userPrivacyParam.getAllowMyVideo());
        }
        if (userPrivacyParam.getAllowMyArticle() != null) {
            userBasicPrivacy.setAllowMyArticle(userPrivacyParam.getAllowMyArticle());
        }
        // 用户交互方面的隐私设置
        if (userPrivacyParam.getShowNearbyArticle() != null) {
            userBasicPrivacy.setShowNearbyArticle(userPrivacyParam.getShowNearbyArticle());
        }
        if (userPrivacyParam.getAllowAddMe() != null) {
            userBasicPrivacy.setAllowAddMe(userPrivacyParam.getAllowAddMe());
        }
        if (userPrivacyParam.getAllowContactForMe() != null) {
            userBasicPrivacy.setAllowContactForMe(userPrivacyParam.getAllowContactForMe());
        }
        if (userPrivacyParam.getAllowCoolFaceMe() != null) {
            userBasicPrivacy.setAllowCoolFaceMe(userPrivacyParam.getAllowCoolFaceMe());
        }
        if (userPrivacyParam.getAllowRecommendMe() != null) {
            userBasicPrivacy.setAllowRecommendMe(userPrivacyParam.getAllowRecommendMe());
        }
        if (userPrivacyParam.getAllowNearbyMe() != null) {
            userBasicPrivacy.setAllowNearbyMe(userPrivacyParam.getAllowNearbyMe());
        }
        if (userPrivacyParam.getAutoAgreeAddMe() != null) {
            userBasicPrivacy.setAutoAgreeAddMe(userPrivacyParam.getAutoAgreeAddMe());
        }
        // 只更新有值的属性
        return queryFactory.update(qUser)
                .populate(userBasicPrivacy)
                .where(qUser.userId.eq(userPrivacyParam.getUserId()))
                .execute();
    }

    @Override
    public boolean isCanSeeMyFriends(String userId, String otherId) {
        if (!StringUtils.hasText(userId) || !StringUtils.hasText(otherId)) {
            throw new AppException("UserInformationIsEmpty");
        }
        return queryFactory.selectFrom(qUser)
                .where(qUser.userId.eq(userId))
                // 禁止查看我的好友的不行
                .where(qUser.allowMyFriends.ne(0))
                // 允许查看我的好友
                .where(qUser.allowMyFriends.eq(1)
                        // 或者在我设置的允许的列表中
                        .or(SQLExpressions.selectOne().from(qPrivacy)
                                .where(qPrivacy.userId.eq(qUser.userId))
                                .where(qPrivacy.otherId.eq(otherId))
                                .where(qPrivacy.type.eq(PrivacyConst.TYPE_MY_FRIENDS))
                                .limit(1).exists())
                ).fetchCount() > 0;
    }

}
